package com.itaming.lycheeframework.support.id;

import com.itaming.lycheeframework.support.utils.DateTimeUtil;
import com.itaming.lycheeframework.support.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.time.LocalDateTime;

/**
 * 雪花算法ID生成器
 *
 * @author A.Ming
 */
@Slf4j
public class SnowflakeIdGenerator {

    /**
     * 默认基准时间
     * <p>
     * 没有特殊含义，只是基于编写这个类的时间选了一个能生成19位ID的时间点
     */
    private static final LocalDateTime DEFAULT_START_TIME = LocalDateTime.of(2016, 1, 1, 0, 0, 0);

    /**
     * 序列位数
     */
    private static final long SEQUENCE_BITS = 12L;

    /**
     * 工作节点ID位数
     */
    private static final long WORKER_ID_BITS = 5L;

    /**
     * 数据中心ID位数
     */
    private static final long DATA_CENTER_ID_BITS = 5L;

    /**
     * 序列掩码
     */
    private static final long SEQUENCE_MASK = (1L << SEQUENCE_BITS) - 1;

    /**
     * 工作节点ID最大值
     */
    private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;

    /**
     * 数据中心ID最大值
     */
    private static final long MAX_DATA_CENTER_ID = (1L << DATA_CENTER_ID_BITS) - 1;

    /**
     * 工作节点ID偏移量
     */
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;

    /**
     * 数据中心ID偏移量
     */
    private static final long DATA_CENTER_ID_SHIFT = WORKER_ID_SHIFT + WORKER_ID_BITS;

    /**
     * 时间戳偏移量
     */
    private static final long TIMESTAMP_SHIFT = DATA_CENTER_ID_SHIFT + DATA_CENTER_ID_BITS;

    /**
     * 基准时间戳
     * <p>
     * 此值确定后不能更改(至少在项目生命周期内不能更改)，
     * 否则可能导致生成的 ID 出现重复或无序问题！
     */
    private static final long TWEPOCH = DateTimeUtil.toEpochMilli(DEFAULT_START_TIME);

    /**
     * 时钟回拨限制
     */
    private static final long CLOCK_BACKWARD_LIMIT = 5L;

    /**
     * 工作节点ID
     */
    private final long workerId;

    /**
     * 数据中心ID
     */
    private final long dataCenterId;

    /**
     * 同一毫秒内的序列
     */
    private long sequence = 0L;

    /**
     * 上一次生产ID的时间戳
     */
    private long lastTimestamp = -1L;

    /**
     * 雪花算法ID生成器
     */
    public SnowflakeIdGenerator() {
        this(null);
    }

    /**
     * 雪花算法ID生成器
     *
     * @param inetAddress IP地址对象
     */
    public SnowflakeIdGenerator(InetAddress inetAddress) {
        dataCenterId = getDataCenterId(inetAddress, MAX_DATA_CENTER_ID);
        workerId = getWorkerId(dataCenterId, MAX_WORKER_ID);
        initLog();
    }

    /**
     * 雪花算法ID生成器
     *
     * @param workerId     工作节点ID
     * @param dataCenterId 数据中心ID
     */
    public SnowflakeIdGenerator(long workerId, long dataCenterId) {
        Assert.isTrue(workerId >= 0L && workerId <= MAX_WORKER_ID, String.format("workerId must be greater than 0 and less than %d.", MAX_WORKER_ID));
        Assert.isTrue(dataCenterId >= 0L && dataCenterId <= MAX_DATA_CENTER_ID, String.format("dataCenterId must be greater than 0 and less than %d.", MAX_DATA_CENTER_ID));
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
        initLog();
    }

    /**
     * 获取下一个ID
     *
     * @return ID
     */
    public synchronized long nextId() {
        // 获取当前时间戳
        long timestamp = getCurrentTimeMillis();

        // 时钟回拨
        if (timestamp < lastTimestamp) {
            // 获取回拨偏移量
            long offset = lastTimestamp - timestamp;

            // 超过回拨限制，抛出异常
            if (offset > CLOCK_BACKWARD_LIMIT) {
                throw new RuntimeException(String.format("Clock moved backwards, refusing to generate id for %d milliseconds", offset));
            }

            // 未超出回拨限制，尝试修复
            try {
                wait(offset << 1);
                timestamp = getCurrentTimeMillis();
                if (timestamp < lastTimestamp) {
                    throw new RuntimeException(String.format("Clock moved backwards, refusing to generate id for %d milliseconds", offset));
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        // 同一毫秒内
        if (timestamp == lastTimestamp) {
            // 序列自增
            sequence = sequence + 1L & SEQUENCE_MASK;
            // 如果序列溢出，等待下一毫秒
            if (sequence == 0L) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 不同毫秒，序列重置为0
            sequence = 0L;
        }

        // 更新生产ID的时间戳
        lastTimestamp = timestamp;

        // 返回ID
        return ((timestamp - TWEPOCH) << TIMESTAMP_SHIFT)
            | (dataCenterId << DATA_CENTER_ID_SHIFT)
            | (workerId << WORKER_ID_SHIFT)
            | sequence;
    }

    /**
     * 初始化日志
     */
    private void initLog() {
        log.debug("SnowflakeIdWorker init, workerId: {}, dataCenterId: {}", workerId, dataCenterId);
    }

    /**
     * 获取数据中心ID
     *
     * @param inetAddress     IP地址对象
     * @param maxDataCenterId 数据中心ID最大值
     * @return 数据中心ID
     */
    private long getDataCenterId(InetAddress inetAddress, long maxDataCenterId) {
        long id = 1L;

        // 根据MAC地址获取数据中心ID
        try {
            if (inetAddress == null) {
                inetAddress = InetAddress.getLocalHost();
            }

            // 根据网卡 MAC 地址获取数据中心ID
            NetworkInterface network = NetworkInterface.getByInetAddress(inetAddress);
            if (network != null) {
                byte[] mac = network.getHardwareAddress();
                if (mac != null) {
                    id = ((0x00ff & (long) mac[mac.length - 2]) | (0xff00 & ((long) mac[mac.length - 1] << 8))) >> 6;
                    id %= maxDataCenterId + 1L;
                }
            }
        } catch (Exception e) {
            log.warn("Get dataCenterId error: {}", e.getMessage());
        }

        return id;
    }

    /**
     * 获取工作节点ID
     *
     * @param dataCenterId 数据中心ID
     * @param maxWorkerId  工作节点ID最大值
     * @return 工作节点ID
     */
    private long getWorkerId(long dataCenterId, long maxWorkerId) {
        StringBuilder mpId = new StringBuilder();

        // 拼接数据中心ID和进程ID
        mpId.append(dataCenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (StringUtil.isNotBlank(name)) {
            mpId.append(name.split("@")[0]);
        }

        return ((long) mpId.toString().hashCode() & 0xffff) % (maxWorkerId + 1L);
    }

    /**
     * 等待下一秒时间戳
     *
     * @param lastTimestamp 上一次生产ID的时间戳
     * @return 下一秒时间戳
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = getCurrentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = getCurrentTimeMillis();
        }
        return timestamp;
    }

    /**
     * 获取当前时间戳
     *
     * @return 当前时间戳
     */
    private long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }


}
